<!-- src/components/VideoUpload/index.vue -->
<template>
  <div class="video-upload">
    <el-upload
      class="upload-demo"
      :action="uploadAction"
      :headers="uploadHeaders"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-exceed="handleExceed"
      accept="video/*"
      v-bind="$attrs"
      v-on="$listeners">
      <el-button size="small" type="primary">{{ buttonText }}</el-button>
      <div slot="tip" class="el-upload__tip">{{ tipText }}</div>
    </el-upload>
    <div v-if="videoUrl" class="video-preview">
      <video :src="videoUrl" controls style="width: 100%; max-width: 300px;"></video>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'VideoUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 1
    },
    buttonText: {
      type: String,
      default: '点击上传'
    },
    tipText: {
      type: String,
      default: '只能上传视频文件，且不超过500MB'
    },
    uploadAction: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: []
    }
  },
  computed: {
    videoUrl() {
      return this.value
    }
  },
  watch: {
    videoUrl: {
      handler(val) {
        if (val && !this.fileList.length) {
          this.fileList = [{
            name: this.getFileNameFromUrl(val),
            url: val
          }]
        }
      },
      immediate: true
    }
  },
  methods: {
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$emit('input', response.data.url)
        this.$emit('success', response, file, fileList)
        this.$message.success('视频上传成功')
      } else {
        this.$message.error(response.msg || '视频上传失败')
        this.fileList = []
      }
    },
    
    handleError(err, file, fileList) {
      this.$emit('error', err, file, fileList)
      this.$message.error('视频上传失败')
      this.fileList = []
    },
    
    beforeUpload(file) {
      const isVideo = file.type.includes('video')
      const isLt500M = file.size / 1024 / 1024 < 500
      
      if (!isVideo) {
        this.$message.error('只能上传视频格式文件!')
      }
      if (!isLt500M) {
        this.$message.error('上传视频大小不能超过 500MB!')
      }
      
      return isVideo && isLt500M
    },
    
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件`)
    },
    
    getFileNameFromUrl(url) {
      if (!url) return 'video.mp4'
      const splitUrl = url.split('/')
      return splitUrl[splitUrl.length - 1] || 'video.mp4'
    }
  }
}
</script>

<style scoped>
.video-preview {
  margin-top: 10px;
}
</style>